using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;

namespace RunAliasCreator
{
	public static class RunAlias
	{
		public static bool Exists(string alias)
		{
			string runAlias = alias;
			if (runAlias.IndexOf('.') < 0) runAlias += ".exe";
			RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths");
			RegistryKey subkey;
			if (key == null)
				throw new AccessViolationException("Access to the registry key was denied by the system.");
			subkey = key.OpenSubKey(runAlias);
			bool exists = (subkey != null);
			if (exists) subkey.Close();
			key.Close();
			return exists;
		}

		public static bool Create(string target, string alias)
		{ return Create(target, alias, true); }
		public static bool Create(string target, string alias, bool overwrite)
		{
			string runAlias = alias;
			if (runAlias.IndexOf('.') < 0) runAlias += ".exe";
			RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths", true);
			RegistryKey subkey;
			if (key == null)
				throw new AccessViolationException("Access to the registry key was denied by the system.");
			subkey = key.OpenSubKey(runAlias, true);
			if (subkey != null && !overwrite)
			{
				subkey.Close();
				key.Close();
				return false;
			}
			if (subkey == null) subkey = key.CreateSubKey(runAlias);
			if (subkey == null)
			{
				key.Close();
				throw new AccessViolationException("Access to the registry key was denied by the system.");
			}
			subkey.SetValue(null, '\"' + target + '\"');
			subkey.Close();
			key.Close();
			return true;
		}

		public static bool Delete(string alias)
		{
			string runAlias = alias;
			if (runAlias.IndexOf('.') < 0) runAlias += ".exe";
			RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths", true);
			RegistryKey subkey;
			if (key == null)
				throw new AccessViolationException("Access to the registry key was denied by the system.");
			subkey = key.OpenSubKey(runAlias, true);
			bool result = false;
			if (subkey != null)
			{
				subkey.Close();
				key.DeleteSubKeyTree(runAlias);
				result = true;
			}
			key.Close();
			return result;
		}

	}
}
